<?php
/**
 * Created by PhpStorm.
 * User: lullabies
 * Date: 2019/5/23
 * Time: 0:41
 */

namespace app\api\controller;
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept,fs-token");
header('Access-Control-Allow-Methods: GET, POST');
use app\api\model\Subjects as SubjectsModel;
use app\api\validate\IDMustBePositiveInt;
use app\api\model\Grade as GradeModel;
use app\api\model\Works as WorksModel;
use function PHPSTORM_META\type;
use think\Db;

/**
 * @title 科目管理
 * @group app
 */
class Subjects extends Base
{
    /**
     * @title 根据科目id获取科目相关信息
     * @author 开发者
     * @url /api/subjects/getInfoById
     * @method POST/GET
     * @description 测试id为1
     * @param name:id require:1 default:null type:int desc:科目id
     * @return name:科目名称
     * @return price:价格
     * @return content:内容
     * @return img:图片地址
     * @return exam_id:考试id
     * @return create_time:创建时间
     * @return update_time:更新时间
     */
    public function getInfoById(){
        //获取科目id
        $id = input('id');
        (new IDMustBePositiveInt())->goCheck();
        $result = SubjectsModel::getInfoById($id);
        if(empty($result)){
            $this->apiReturn(303,'未找到相关信息！');
        }else{
            $this->apiReturn(200,'获取信息成功！',$result);
        }
    }
    /**
     * @title 根据用户id和考试id获取科目排名及作品信息
     * @author 开发者
     * @url /api/subjects/getRankExamUser
     * @method POST/GET
     * @description 测试的用户和考试id均为1
     * @param name:exam_id require:1 default:null type:int desc:考试id
     * @param name:user_id require:1 default:null type:int desc:用户id
     * @return name:作品id
     * @return img:作品图片地址
     * @return create_time:作品创建时间
     * @return score:分数
     * @return username:用户名
     * @return subject_id:科目id
     * @return subject_name:科目名称
     * @return user_id:用户id
     * @return rank:排名
     */
    public function getRankExamUser(){
        $exam_id=input('exam_id');
        $user_id = input('user_id');
        //获取用户考试的单科排名
        $result=Db::query("select score,username,subject_id,subject_name,user_id,(select count(DISTINCT score) from art_grade as g2 where g2.score >= g1.score and g1.subject_id=g2.subject_id) rank 
FROM art_grade as g1 where g1.exam_id=$exam_id and g1.user_id=$user_id order by score desc");
        $arr = array();
        foreach ($result as $k=>$v){
            $subject_id=$v['subject_id'];
            //根据科目和用户id获取作品信息
            $info = WorksModel::getInfoBySubjectUser($subject_id,$user_id)->hidden(['subject_id','user_id','status']);
          //将对象转换为数组
            $info=json_encode($info,true);
            $info=json_decode($info,true);
            $arr[] =array_merge($info,$v);
        }
        $this->apiReturn(200,'查询成功！',$arr);
    }
}